package com.example.demospring.service.assistant;

import com.example.demospring.entity.ConsultationRecord;
import com.example.demospring.dto.assistant.ConsultationRecordDTO;
import com.example.demospring.repository.ConsultationRecordRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ConsultationRecordService {

    @Autowired
    private ConsultationRecordRepository recordRepository;

    public Page<ConsultationRecordDTO> findPage(
            String keyword, String status, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("consultDate").descending());
        // 这里只简单处理过滤，复杂条件请用 Specification
        ExampleMatcher matcher = ExampleMatcher.matchingAll();
        ConsultationRecord probe = new ConsultationRecord();
        if (status != null && !status.isEmpty()) probe.setStatus(status);
        Page<ConsultationRecord> entityPage = recordRepository.findAll(Example.of(probe, matcher), pageable);

        // DTO 转换
        Page<ConsultationRecordDTO> dtoPage = entityPage.map(this::toDTO);

        // 关键字过滤（本地过滤，性能一般，如需高效请用Specification或自定义sql）
        if (keyword != null && !keyword.isEmpty()) {
            dtoPage = new PageImpl<>(
                    dtoPage.getContent().stream().filter(dto ->
                            (dto.getClientName() != null && dto.getClientName().contains(keyword))
                                    || (dto.getSummary()   != null && dto.getSummary().contains(keyword))
                    ).collect(Collectors.toList()),
                    pageable,
                    dtoPage.getTotalElements()
            );
        }

        return dtoPage;
    }

    public ConsultationRecordDTO getById(Integer id) {
        Optional<ConsultationRecord> entity = recordRepository.findById(id);
        return entity.map(this::toDTO).orElse(null);
    }

    public ConsultationRecordDTO saveOrUpdate(ConsultationRecordDTO dto) {
        ConsultationRecord record = new ConsultationRecord();
        if (dto.getId() != null) {
            // 编辑时先查出原始，再覆盖
            Optional<ConsultationRecord> oldOpt = recordRepository.findById(dto.getId());
            if (oldOpt.isPresent()) {
                record = oldOpt.get();
            }
        }
        BeanUtils.copyProperties(dto, record, "id"); // 避免id被覆盖
        if (record.getRecordTime() == null) {
            record.setRecordTime(java.time.LocalDateTime.now());
        }
        ConsultationRecord saved = recordRepository.save(record);
        return toDTO(saved);
    }

    public void delete(Integer id) {
        recordRepository.deleteById(id);
    }

    // ----------- Entity 与 DTO 简单手写互转 ----------
    private ConsultationRecordDTO toDTO(ConsultationRecord record) {
        ConsultationRecordDTO dto = new ConsultationRecordDTO();
        BeanUtils.copyProperties(record, dto);
        return dto;
    }
}